<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Backend_Auth extends Controller_Backend {
	
	public $template = 'backend.auth';
	
	public function before() {
		
		if (Request::current()->action() == 'logout')
		{
			$this->auto_render = FALSE;
		}
		
		parent::before();
	}
	
	public function action_login()
	{
		$view = new View('backend/auth.login');
		
		$errmess = '';
		
		if (isset($_POST['auth']['login']) AND isset($_POST['auth']['password']))
		{
			$logged = FALSE;
			$errmess = 'Не удалось войти.';
			
			$admin = Kohana::$config->load('backend.admin');
			
			if (Captcha::valid($_POST['auth_captcha']))
			{
				foreach ($admin as $login => $hash)
				{
					if (md5($login) == md5($_POST['auth']['login']) AND md5($hash) == md5(md5($_POST['auth']['password'])))
					{
						Cookie::set('backend_login', md5($login));
						Cookie::set('backend_hash', md5(md5($_POST['auth']['password'])));

						$logged = TRUE;
					}
				}
			}
			else
			{
				$errmess = 'Проверочный код неверный.';
			}
			
			if ($logged === TRUE)
			{
				Request::current()->redirect(URL::site(Route::get('backend')->uri(array(
					'directory' => 'backend',
					'controller' => 'home',
					'action' => 'index',
				))));
			}
		}
		
		$view->errmess = $errmess;
		
		$this->template->content = $view;
	}
	
	public function action_logout()
	{
		Cookie::delete('backend_login');
		Cookie::delete('backend_hash');
		
		Request::current()->redirect(URL::site(Route::get('backend')->uri(array(
			'directory' => 'backend',
			'controller' => 'auth',
			'action' => 'login',
		))));
	}
	
}